import * as api from '../../api/api.js';
import * as db from '../../utils/db.js';
import { ASSETS } from '../../config.js';
const app = getApp();
const os = app.os;
let scrollHeight = [0, 0];
let methodMark = 1; //1未下单退出;2已下单退出;3完成支付退出;4支付失败

Component({
  data: {
    assets: ASSETS,
    appType: app.globalData.appType,
    imId: app.globalData.imId, // 客服抖音号
    iosDyPayType: 0, //2=IM支付,3=钻石支付
    isIPhone: app.isIPhone(),
    animation: true,
    isFirst: true,
    isLoading: true,
    isNoPayOrder: false,
    showIosNoTemp: false,
    coin_amount: 0,
    playlet_total: 0,
    rechargeList: [],
    vipList: [],
    cardList: [],
    retainConfig: null,
    currentOrder: false,
    currentGearType: 1,
    defaultData: false,
    showGuideLayer: false,
    orderId: ''
  },
  properties: {
    show:{
      type: Boolean,
      value: false,
      observer(value){
        if (value) {
          methodMark = 1;
          this.setData({
            appType: app.globalData.appType,
            imId: app.globalData.imId,
            showIosNoTemp: !app.isCanBuy()
          });
          this.refreshRechargeList();
          this.sendAppLogs('pay', 1);
        }
      }
    },
    height: {
      type: String,
      value: '65vh'
    },
    currentVideo: {
      type: Object,
      value: {},
      observer(value){
        if (value) {
          this.setData({
            currentVideo: value
          });
        }
      }
    },
    showVip: {
      type: Boolean,
      value: false
    }
  },

  methods: {

    refreshRechargeList(){
      // if (this.data.isFirst) {
        this.setData({isLoading: true});
      // }
      api.getRechargeList({
        playlet_id: this.data.currentVideo?.playlet_id || 0,
      }).then(res => {
        if (res.code == 200) {
          app.echo('api getRechargeList', res);
          this.setData({
            isFirst: false,
            retainConfig: res.data.retain_config,
            defaultData: res.data.default_gear,
            rechargeList: res.data.common_list,
            vipList: res.data.vip_list,
            cardList: res.data.card_list,
            coin_amount: res.data.coin_amount,
            playlet_total: res.data?.playlet_total || 0,
            iosDyPayType: res.data?.iosDyPayType || 0,
            isLoading: false
          });
        }else{
          this.setData({isLoading: false});
          return app.Tips({title: res.msg});
        }
      }).catch(err => {
        this.setData({isLoading: false});
      });
    },

    onCreateOrder(e){
      if (!app.isCanBuy()) {
        app.Tips({title: 'iOS 暂不支持购买'});
        return;
      }

      // 未支付订单
      if (this.data.isNoPayOrder) {
        this.queryOrder(2);
        return;
      }
      
      const { item } = e.currentTarget.dataset;
      os.showLoading({
        title: '请稍候...',
        mask: true
      });
      this.setData({
        currentOrder: item
      });
      let logsData = app.getLogsData('pay', 4, {
        payment_id: item.gear_id,
        method_id: this.data.currentVideo?.playlet_id || 0,
        method_cid: this.data.currentVideo?.num || 0
      });
      api.createOrder({
        playlet_id: this.data.currentVideo?.playlet_id || 0,
        gear_id: item.gear_id,
        logs: JSON.stringify(logsData)
      }).then(res => {
        os.hideLoading({});
        if (res.code == 200) {
          methodMark = 2;
          app.echo('createOrder', res.data);
          const data = JSON.parse(res.data.data);
          const payScene = data?.payScene || "";
          const currency = data?.currency || "";
          this.setData({
            orderId: res.data.order_id,
            currentGearType: item.gear_type_id,
            iosDyPayType: payScene === "IM" ? 2:(currency === 'DIAMOND' ? 3:0)
          });
          this.createOrder(res.data);
        }else{
          app.Tips({title: res.msg});
          if (res.code === 201) {
            this.confirm();
            return;
          }
          this.sendAppLogs('pay', 6, {
            method_mark: res.msg,
            method_mark_1: res.code
          });
        }
      }).catch(err => {
        os.hideLoading({});
      });
    },

    createOrder(res){
      os.requestOrder({
        data: res.data, 
        byteAuthorization: res.byteAuthorization,
        success: (res) => {
          // app.echo(res)
          app.echo('orderId', res.orderId);
          this.openOrderPayment(res.orderId);
        },
        fail: (res) => {
          app.echo('requestOrder error', res);
          app.Tips({title: '下单失败', icon: 'fail'});
          this.sendAppLogs('pay', 6, {
            method_mark: res.errMsg,
            method_mark_1: res.errNo
          });
        },
      });
    },

    openOrderPayment(orderId){
      os.showLoading({
        title: '安全支付中...',
        mask: true
      });
      let parms = {
        orderId: orderId,
        success: (res) => {
          os.hideLoading({});
          methodMark = 3;
          this.setData({isNoPayOrder: true});
          db.saveNoPayOrder(this.data.orderId);
          this.queryOrder();
        },
        fail: (res) => {
          os.hideLoading({});
          methodMark = 4;
          app.echo('getOrderPayment error', res);
          if (res.errNo === 9) {
            this.setData({isNoPayOrder: true});
            db.saveNoPayOrder(this.data.orderId);
            this.queryOrder(3);
          } 
          if (res.errNo === 4) {
            app.Tips({title: '支付取消', icon: 'fail'});
          } 
          if (res.errNo !== 4 && res.errNo !== 9) {
            app.Tips({title: '支付失败', icon: 'fail'});
          } 

          this.sendAppLogs('pay', 6, {
            method_mark: res.errMsg,
            method_mark_1: res.errNo
          });
        },
        complete: (res) => {
          // db.saveNoPayOrder(this.data.orderId);
          // this.setData({isNoPayOrder: true});
        }
      };

      if (this.data.iosDyPayType === 2 && app.isIPhone() && os.canIUse("getOrderPayment.object.immediate")) {
        parms.immediate = false;
        parms.imId = app.globalData.imId;
      }

      app.echo('orderPayment parms', parms);
      os.getOrderPayment(parms);
    },

    queryOrder(type = 0){
      os.showLoading({
        title: '请稍候...',
        mask: true
      });
      api.queryOrder({
        order_id: this.data.orderId
      }).then(res => {
        os.hideLoading({});
        if (res.code == 200) {
          if (type === 4) {
            app.Tips({title: '充值已到账'});
          }
          this.confirm();
        }else{
          app.echo('queryOrder error', res);
          // app.Tips({title: res.msg});
          this.sendAppLogs('pay', 6, {
            method_mark: res.msg,
            method_mark_1: res.code
          });
          if (type === 0) {
            app.Tips({title: '稍后查看到账情况'});
          }
          if (type === 1) {
            this.cancel();
          }
          if (type === 2) {
            this.setData({isNoPayOrder: false});
            app.Tips({title: '请稍后重试'});
          }
          if (type === 3) {
            app.Tips({title: '支付失败', icon: 'fail'});
          }
          if (type === 4) {
            this.setData({showGuideLayer: true});
          }
        }
      }).catch(err => {
        os.hideLoading({});
        if (type === 1) {
          this.cancel();
        }
        if (type === 0 && this.data.currentGearType !== 1) {
          this.confirm();
        }
      });
    },
    
    onPlatformImError(e){
      app.echo('im error', e);
      app.Tips({
        title: "即将开通客服，请耐心等待"
      });
    },

    onPlatformImSucess: function(e){
      this.sendAppLogs('app', 4, {
        method_mark: 'im',
        method_mark_1: '官方客服'
      });
    },

    toAgreementPage(e){
      app.goNewsPage(parseInt(e.currentTarget.dataset.id));
    },

    checkOrder(){
      // 未支付订单
      if (this.data.isNoPayOrder) {
        this.queryOrder(4);
        return;
      }
      this.setData({showGuideLayer: true});
    },

    onGuideCancel(){
      this.setData({showGuideLayer: false});
    },

    closeDialog(){
      // 未支付订单
      if (this.data.isNoPayOrder) {
        this.queryOrder(1);
        return;
      }
      this.cancel();
    },

    confirm() {
      this.setData({
        show: false,
        isNoPayOrder: false
      });

      this.triggerEvent('confirm', {
        cData: this.data.currentOrder
      });

      db.delNoPayOrder();

      this.sendAppLogs('pay', 3, {
        method_mark: 3
      });
    },

    cancel() {
      this.setData({
        show: false,
        isNoPayOrder: false
      });

      const { retainConfig,currentOrder,defaultData } = this.data;
      let pdata = defaultData;
      if(retainConfig?.recommend_type === 2 && currentOrder){
        pdata = currentOrder;
      }

      this.triggerEvent('cancel', {
        cData: this.data.currentOrder,
        pData: pdata
      });

      this.sendAppLogs('pay', 3, {
        method_mark: methodMark
      });
    },

    onScroll: function(e) {
      this.onSlideEvent(e);
    },
  
    onSlideEvent: function(e) {
      const that = this;
      scrollHeight[1] = parseInt(e.detail.scrollTop);

      if (this.slideTimeId) {
        clearTimeout(this.slideTimeId);
      }
      
      this.slideTimeId = setTimeout(() => {
        clearTimeout(that.slideTimeId);

        if(scrollHeight[0] !== scrollHeight[1]){
          const sHeight = [scrollHeight[0], scrollHeight[1]];

          that.triggerEvent('scroll', {scrollHeight: sHeight});

          this.sendAppLogs('pay', 2, {
            method_mark: sHeight[0],
            method_mark_1: sHeight[1],
          });

          scrollHeight[0] = scrollHeight[1];
        }
      }, 300);
    },

    /**
     * 发送日志
     */
    sendAppLogs(logType = 'app', markType = 1, data = {}){
      const currentVideo = this.data.currentVideo;
      let rData = {};
      if (currentVideo) {
        rData = {
          method_id: currentVideo.playlet_id || 0, 
          method_cid: currentVideo.num || 0,
          method_rid: parseInt(currentVideo?.fromPlayletId || 0),
          method_amount: currentVideo.currentTime || 0
        };
      }
      rData.order_id = this.data.orderId;
      Object.assign(rData, data);
      app.sendAppLogs(logType, markType, rData);
    },
  }
})